package com.module.ble.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import com.common.base.app.extras.no
import com.common.base.utils.ViewUtils.getColor
import com.module.ble.R

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：12/7/2025
 *
 * 描述：睡眠最佳区间进度条
 * 带有最佳区间标识的水平进度条控件
 * 修订历史：
 *
 */
class SleepOptimalRangeProgressBar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 进度条背景画笔
    private val backgroundPaint: Paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.FILL
    }

    // 进度条前景画笔
    private val progressPaint: Paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.FILL
    }

    // 最佳区间竖线画笔
    private val optimalLinePaint: Paint = Paint().apply {
        isAntiAlias = true
        style = Paint.Style.STROKE
        strokeWidth = 4f
        strokeCap = Paint.Cap.ROUND
    }

    // 进度条属性
    private var progress: Int = 0
    private var maxProgress: Int = 100
    private var minProgress: Int = 0

    // 最佳区间属性
    private var optimalRangeStart: Float = 0f
    private var optimalRangeEnd: Float = 0f

    // 颜色属性
    private var backgroundColor: Int = getColor(R.color.white)
    private var progressColor: Int = getColor(R.color.product_color)
    private var optimalLineColor: Int = getColor(R.color.c_017270)

    // 进度条高度
    private var progressBarHeight: Float = 12f

    // 进度条圆角半径
    private var cornerRadius: Float = 0f

    // 最佳区间竖线高度（相对于进度条的倍数）
    private var optimalLineHeightRatio: Float = 1f

    init {
        @SuppressLint("Recycle")
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.SleepOptimalRangeProgressBar)

        // 从XML属性中获取值
        progress = typedArray.getInt(R.styleable.SleepOptimalRangeProgressBar_progress, 0)
        maxProgress = typedArray.getInt(R.styleable.SleepOptimalRangeProgressBar_maxProgress, 100)
        minProgress = typedArray.getInt(R.styleable.SleepOptimalRangeProgressBar_minProgress, 0)

        optimalRangeStart = typedArray.getFloat(R.styleable.SleepOptimalRangeProgressBar_optimalRangeStart, 0f)
        optimalRangeEnd = typedArray.getFloat(R.styleable.SleepOptimalRangeProgressBar_optimalRangeEnd, 0f)

        backgroundColor = typedArray.getColor(R.styleable.SleepOptimalRangeProgressBar_backgroundColor, backgroundColor)
        progressColor = typedArray.getColor(R.styleable.SleepOptimalRangeProgressBar_progressColor, progressColor)
        optimalLineColor = typedArray.getColor(R.styleable.SleepOptimalRangeProgressBar_optimalLineColor, optimalLineColor)

        progressBarHeight = typedArray.getDimension(R.styleable.SleepOptimalRangeProgressBar_progressBarHeight, progressBarHeight)
        cornerRadius = typedArray.getDimension(R.styleable.SleepOptimalRangeProgressBar_cornerRadius, cornerRadius)
        optimalLineHeightRatio = typedArray.getFloat(R.styleable.SleepOptimalRangeProgressBar_optimalLineHeightRatio, optimalLineHeightRatio)

        typedArray.recycle()

        // 设置画笔颜色
        updatePaintColors()
    }

    private fun updatePaintColors() {
        backgroundPaint.color = backgroundColor
        progressPaint.color = progressColor
        optimalLinePaint.color = optimalLineColor
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val desiredHeight = (progressBarHeight * optimalLineHeightRatio + paddingTop + paddingBottom).toInt()
        val height = resolveSize(desiredHeight, heightMeasureSpec)
        val width = MeasureSpec.getSize(widthMeasureSpec)
        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        val availableWidth = width - paddingLeft - paddingRight
        val centerY = height / 2f

        // 绘制背景进度条
        val backgroundRect = RectF(
            paddingLeft.toFloat(),
            centerY - progressBarHeight / 2,
            paddingLeft + availableWidth.toFloat(),
            centerY + progressBarHeight / 2
        )
        canvas.drawRoundRect(backgroundRect, cornerRadius, cornerRadius, backgroundPaint)

        // 绘制当前进度
        if (progress > minProgress) {
            val progressWidth = availableWidth * (progress - minProgress).toFloat() / (maxProgress - minProgress)
            val progressRect = RectF(
                paddingLeft.toFloat(),
                centerY - progressBarHeight / 2,
                paddingLeft + progressWidth,
                centerY + progressBarHeight / 2
            )
            canvas.drawRoundRect(progressRect, cornerRadius, cornerRadius, progressPaint)
        }

        // 绘制最佳区间竖线
        ((optimalRangeStart <= 0 && optimalRangeEnd <= 0) || (optimalRangeEnd<optimalRangeStart)).no {
            // 绘制最佳区间竖线
            val lineHeight = progressBarHeight * optimalLineHeightRatio
            val lineTop = centerY - lineHeight / 2
            val lineBottom = centerY + lineHeight / 2

            // 绘制最佳区间开始线
            val startLineX = paddingLeft + availableWidth * (optimalRangeStart - minProgress).toFloat() / (maxProgress - minProgress)
            if (startLineX >= paddingLeft && startLineX <= paddingLeft + availableWidth) {
                canvas.drawLine(startLineX, lineTop, startLineX, lineBottom, optimalLinePaint)
            }

            // 绘制最佳区间结束线
            val endLineX = paddingLeft + availableWidth * (optimalRangeEnd - minProgress).toFloat() / (maxProgress - minProgress)
            if (endLineX >= paddingLeft && endLineX <= paddingLeft + availableWidth) {
                canvas.drawLine(endLineX, lineTop, endLineX, lineBottom, optimalLinePaint)
            }
        }
    }

    // 公共方法
    fun setMaxProgress(progress: Int) {
        this.maxProgress = progress
        invalidate()
    }
    fun setProgress(progress: Int) {
        this.progress = progress.coerceIn(minProgress, maxProgress)
        invalidate()
    }

    fun getProgress(): Int = progress

    fun setOptimalRange(start: Float, end: Float) {
        this.optimalRangeStart = start.coerceIn(minProgress.toFloat(), maxProgress.toFloat())
        this.optimalRangeEnd = end.coerceIn(minProgress.toFloat(), maxProgress.toFloat())
        invalidate()
    }

    fun setProgressBackgroundColor(@ColorRes colorRes: Int) {
        this.backgroundColor = ContextCompat.getColor(context, colorRes)
        updatePaintColors()
        invalidate()
    }

    fun setProgressColor(@ColorRes colorRes: Int) {
        this.progressColor = ContextCompat.getColor(context, colorRes)
        updatePaintColors()
        invalidate()
    }

    fun setOptimalLineColor(@ColorRes colorRes: Int) {
        this.optimalLineColor = ContextCompat.getColor(context, colorRes)
        updatePaintColors()
        invalidate()
    }

    fun setProgressBarHeight(height: Float) {
        this.progressBarHeight = height
        requestLayout()
    }

    fun setCornerRadius(radius: Float) {
        this.cornerRadius = radius
        invalidate()
    }
}